package com.wan37.logic.team;

import com.wan37.logic.service.cache.UserServiceCache;
import com.wan37.logic.team.cache.TeamCache;
import com.wan37.logic.team.domain.vo.TeamVO;
import com.wan37.logic.team.util.TeamRouteUtil;
import com.wan37.protobuf.constant.CommonTeam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @author : luoyong
 * @date : 2020-07-30 21:11
 **/
@Component
public class TeamManager {
    @Autowired
    private UserServiceCache userServiceCache;
    @Autowired
    private TeamRouteUtil teamRouteUtil;
    @Autowired
    private TeamCache teamCache;
    public void out(String userId){
        String teamName = userServiceCache.getUserServiceMap().get(userId).getTeamName();
        if (teamName != null) {
            TeamVO teamVO2 = teamCache.getTeamInMap().get(teamName).getTeamVO();
            if (teamVO2.getCaptain().equals(userId)) {
                for (String userId1 : teamVO2.getUserIdList()) {
                    userServiceCache.getUserServiceMap().get(userId1).setTeamName(null);
                    teamRouteUtil.sendTeamResponse(CommonTeam.OUT, new ArrayList<>(), userId1);
                }
                teamCache.getTeamInMap().remove(teamName);
            } else {
                teamVO2.getUserIdList().remove(userId);
                teamRouteUtil.sendTeamResponse(CommonTeam.OUT, new ArrayList<>(), userId);
                for (String userId1 : teamVO2.getUserIdList()) {
                    teamRouteUtil.sendTeamResponse(CommonTeam.UPDATE, teamVO2, userId1);
                }
                //用户缓存中删除所在队伍名称
                userServiceCache.getUserServiceMap().get(userId).setTeamName(null);
            }
        }
    }
}
